from pymongo import MongoClient
import config
import util


class Client:
    """
        客户端连接封装
    """
    _client = None
    _config = None
    _instance = None

    def __new__(cls, *args, **kwargs):
        # 单例模式
        if cls._instance is None:
            cls._config = config.Config()
            cls._instance = object.__new__(cls)
            cls._client = cls._instance._connect()
        return cls._instance

    def _connect(self):
        conn_str = f"mongodb://{self._config.username}:{self._config.password}@{self._config.host}:{self._config.port}/{self._config.database}?retryWrites=true&w=majority"
        client = MongoClient(conn_str, serverSelectionTimeoutMS=self._config.selectionTimeout)
        util.debug(client.server_info(), 'client init')
        return client

    def get_collection(self, collection):
        """
        获得数据表
        :param collection: 要连接的表
        :return: 数据表的句柄
        """
        return self._client.get_database(self._config.database)[collection]

    def has_collection(self, collection):
        """
        判断数据表是否存在
        :param collection: 要连接的表
        :return: 判断结果
        """
        util.debug(self._client.get_database(self._config.database).list_collection_names(), 'existed collections : ')
        return collection in self._client.get_database(self._config.database).list_collection_names()


class DataBaseError(RuntimeError):
    """
    自定义异常
    """

    def __init__(self, reason):
        super(DataBaseError, self).__init__()
        self.reason = reason

    def print_reason(self):
        print("!!! error !!! " + self.reason)
